from flask import Flask, render_template, request, escape
from flask_bootstrap import Bootstrap
from weather import weather
from traffic import traffic
# 调用模块

app = Flask(__name__)
bootstrap = Bootstrap(app)


# 编写日志，打开viewlog.log记录日志数据
def log_request(req: "flask request", res: str):
    with open("viewlog.log", "a") as log:
        print(req.form, req.remote_addr, req.user_agent, res, file=log, sep="|")


# 首页，内涵天气查询功能，获取city信息
@app.route('/entry', methods=['post', 'get'])
def hello_entry():
    return render_template('entry.html')

# 交通路况查询页，获取name（道路），city信息
@app.route('/traffic', methods=['post', 'get'])
def the_traffice():
    return render_template('traffic.html')

# 出行笔记页
@app.route('/blog', methods=['post', 'get'])
def the_blog():
    return render_template('blog.html')

# 登录页，http://secyly.pythonanywhere.com/默认页
@app.route('/')
@app.route("/login", methods=['get'])
def index() -> 'html':
    title = '出行小助手'
    return render_template("login.html",
                           the_title=title)


# 天气查询结果页
@app.route("/get_weather", methods=["post"])
def get_weather():
    city = request.form.get("city")# 获取的城市信息
    results = weather(city)# 请求结果
    row_city = results['lives'][0]['city']# 城市
    row_weather = results['lives'][0]['weather']# 天气
    row_temperature = results['lives'][0]['temperature']# 温度
    row_winddirection = results['lives'][0]['winddirection']# 风向
    row_windpower=results['lives'][0]['windpower']# 风力
    row_humidity=results['lives'][0]['humidity']# 湿度
    row_reporttime=results['lives'][0]['reporttime']# 数据更新时间
    log_request(request, results)# 日志记录
    return render_template('get_weather.html',
                           the_row_city=str(row_city),
                           the_row_weather=str(row_weather),
                           the_row_temperature=str(row_temperature),
                           the_row_winddirection=str(row_winddirection),
                           the_row_windpower=str(row_windpower),
                           the_row_humidity=str(row_humidity),
                           the_row_reporttime=str(row_reporttime))


# 交通路况查询页
@app.route("/get_traffic", methods=["post"])
def get_traffic():
    city = request.form.get("now_city")# 获取的城市信息
    name = request.form.get("name")# 获取的道路信息
    results = traffic(name,city)# 请求结果
    row_tr_description = results['trafficinfo']['description'] ## 描述：具体道路描述
    row_expedite = results['trafficinfo']['evaluation']['expedite']# 畅通所占百分比
    row_congested = results['trafficinfo']['evaluation']['congested']#缓行所占百分比
    row_blocked = results['trafficinfo']['evaluation']['blocked']#拥堵所占百分比
    row_unknown=results['trafficinfo']['evaluation']['unknown']#未知路段所占百分比
    row_status=results['trafficinfo']['evaluation']['status']#路况级别
    row_description=results['trafficinfo']['evaluation']['description']# 路况判断
    log_request(request, results)# 记录日志
    return render_template('get_traffic.html',
                           the_name=name,
                           the_row_tr_description=str(row_tr_description),
                           the_row_expedite=row_expedite,
                           the_row_congested=row_congested,
                           the_row_blocked=row_blocked,
                           the_row_unknown=row_unknown,
                           the_row_status=str(row_status),
                           the_row_description=str(row_description))


# 系统日志页面
@app.route("/viewlog")
def view_log():
    contents = []
    with open("viewlog.log", "r") as log:
        for line in log:
            contents.append([])
            for item in line.split("|"):
                contents[-1].append(escape(item))
    len(contents)# 日志条数
    return render_template('viewlog.html',
                           the_len = len(contents),
                           the_data=contents)



if __name__ == '__main__':
    app.run(debug=True)